#include "SoftwareSpi.h"


SoftwareSpi::SoftwareSpi(SoftwareSpiConfig c,
	BitPointer& sck,
	BitPointer& miso,
	BitPointer& mosi,
	BitPointer& ss)
{
	config = c;
	
	if(config.slave==0) //this should be correct I think.
	{
		MISO = Shifter(c.dataSize, miso, 0,0);
		MOSI = Shifter(c.dataSize, mosi, 1,1);
	}
	else
	{
		MISO = Shifter(c.dataSize, miso, 1,1);
		MOSI = Shifter(c.dataSize, mosi, 0,0);
	}
	SS = ss;
	watcher = EdgeWatcher(sck, 1);
}

bool SoftwareSpi::getFinished()
{
	if(config.finished == 1)
		return true;
	else
		return false;
}
void SoftwareSpi::sendBit()
{
	if(config.slave==0) 
		MISO.shift();
 	else 
		MOSI.shift();
}
BitArray SoftwareSpi::get()
{
	if(config.slave==0)
		return MOSI.get();
	else
		return MISO.get();
}
void SoftwareSpi::set(BitArray& a)
{
	if(config.slave==0)
		MISO.set(a);
	else
		MOSI.set(a);
}
void SoftwareSpi::receiveBit()
{
	if(config.slave==0) 
		MOSI.shift();
 	else 
		MISO.shift();
}

void SoftwareSpi::run()
{
	watcher.run();
	if(config.CPOL == 0 && config.CPHA == 0)
	{
		if(watcher.rising()==1)
			receiveBit();
		else if(watcher.falling()==1)
			sendBit();
	}
	else if(config.CPOL == 0 && config.CPHA == 1)
	{
		if(watcher.falling()==1)
			receiveBit();
		else if(watcher.rising()==1)
			sendBit();
	}
	else if(config.CPOL == 1 && config.CPHA == 0)
	{
		if(watcher.falling()==1)
			receiveBit();
		else if(watcher.rising()==1)
			sendBit();			
	}
	else if(config.CPOL == 1 && config.CPHA == 1)
	{
		if(watcher.rising()==1)
			receiveBit();
		else if(watcher.falling()==1)
			sendBit();
	}
	//check if the transmission is finished
	if(MISO.getFinished()==1 && MOSI.getFinished()==1)
		config.finished = 1;
	else
		config.finished = 0;
}

